﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using BusinessLogic.BusinessEntity.Entities;
using UserInterface.ClientApplication.Exceptions;
using UserInterface.ClientApplication.UIEntity;

namespace UserInterface.ClientApplication
{
	public partial class MainForm : Form, IForm
	{
		private string RateText = "";
		public MainForm()
		{
			InitializeComponent();
		}
		ClientView c = new ClientView();

		private void CreateToolStripFileMenuItem_Click(object sender, EventArgs e)
		{
			InvoiceForm f = new InvoiceForm();
			fm.Param = -1;
			if (f.Show(fm) != DialogResult.Yes)
			{
				RAGridView.DataSource = fm.GetAllRA();
			}
			RAGridView.Refresh();
			
		}
	
		private void MainForm_Load(object sender, EventArgs e)
		{
			InitDefalultData();
			CreateGridViewHeader();
			RAGridView.DataSource = fm.GetAllRA();
			SendedRaDataGridView.DataSource = fm.GetSendedRA();
			UpdateTimer.Enabled = false;
			if (RAGridView.SelectedCells.Count > 0)
			{
				RAGridView_CellEnter(RAGridView, new DataGridViewCellEventArgs(0, RAGridView.SelectedCells[0].RowIndex));
			}else
			{
				RAGridView_CellEnter(RAGridView, new DataGridViewCellEventArgs(0, -1));
			}
		}

		private void CreateGridViewHeader()
		{
			RAGridView.AutoGenerateColumns = false;

			DataGridViewTextBoxColumn NumberColumn = new DataGridViewTextBoxColumn();
			NumberColumn.DataPropertyName = "Number";
			NumberColumn.HeaderText = "Номер";

			DataGridViewTextBoxColumn StatusColumn = new DataGridViewTextBoxColumn();
			StatusColumn.DataPropertyName = "Status";
			StatusColumn.HeaderText = "Статус";
			StatusColumn.Width = 85;

			DataGridViewTextBoxColumn TotalAmount = new DataGridViewTextBoxColumn();
			TotalAmount.DataPropertyName = "TotalAmount";
			TotalAmount.HeaderText = "Сумма";

			DataGridViewTextBoxColumn CurrencyColumn = new DataGridViewTextBoxColumn();
			CurrencyColumn.DataPropertyName = "Currency";
			CurrencyColumn.HeaderText = "Валюта";
			CurrencyColumn.Width = 60;

			RAGridView.Columns.Add(NumberColumn);
			RAGridView.Columns.Add(StatusColumn);
			RAGridView.Columns.Add(TotalAmount);
			RAGridView.Columns.Add(CurrencyColumn);

			var DateColumn = new DataGridViewTextBoxColumn();
			DateColumn.DataPropertyName = "IssueDate";
			DateColumn.HeaderText = "Дата обработки";
			DateColumn.Width = 100;

			NumberColumn = new DataGridViewTextBoxColumn();
			NumberColumn.DataPropertyName = "Number";
			NumberColumn.HeaderText = "Номер";

			StatusColumn = new DataGridViewTextBoxColumn();
			StatusColumn.DataPropertyName = "Status";
			StatusColumn.HeaderText = "Статус";
			StatusColumn.Width = 85;

			TotalAmount = new DataGridViewTextBoxColumn();
			TotalAmount.DataPropertyName = "TotalAmount";
			TotalAmount.HeaderText = "Сумма";

			CurrencyColumn = new DataGridViewTextBoxColumn();
			CurrencyColumn.DataPropertyName = "Currency";
			CurrencyColumn.HeaderText = "Валюта";
			CurrencyColumn.Width = 60;

			SendedRaDataGridView.AutoGenerateColumns = false;
			SendedRaDataGridView.Columns.Add(NumberColumn);
			SendedRaDataGridView.Columns.Add(StatusColumn);
			SendedRaDataGridView.Columns.Add(TotalAmount);
			SendedRaDataGridView.Columns.Add(CurrencyColumn);
			SendedRaDataGridView.Columns.Add(DateColumn);
		}

		private void InitDefalultData()
		{
			new ExceptionCatcher().Execute(()=>
			                               {
			                               	fm.GetAllCurrency();
			                               });
			
			//fm.AddCurrency(new CurrencyView(new Currency() { Code = "342", Name = "BYR" }));
			//fm.AddCurrency(new CurrencyView(new Currency(){ Code = "167", Name = "RUR" }));
			//fm.AddCurrency(new CurrencyView(new Currency() { Code = "101", Name = "EUR" }));
			//fm.AddCurrency(new CurrencyView(new Currency() { Code = "555", Name = "USD" }));
			
		}
		#region IForm Members

		public FormManager fm { get; set; }


		public DialogResult Show(FormManager fm)
		{
			this.fm = fm;
			return ShowDialog();
		}

		#endregion



		private void RAGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{

		}

		private void CloseToolStripFileMenuItem_Click(object sender, EventArgs e)
		{
			Close();

		}

	
		private void StatusToolStripMenuItem_Click(object sender, EventArgs e)
		{
			BaseFormGridArea b = new BaseFormGridArea();
			fm.Param = "status";
			b.Show(fm);
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			Application.Exit();
		}


		public void UpdateInfo()
		{

			new ExceptionCatcher().Execute(() =>
			                               {
			                               	fm.UpdateRemittanceAdvice();
			                               	UdpateCurrencyRate();
			                               });
		}

		private void UdpateCurrencyRate()
		{
			//RateLabel.Text = "";
			stCurrencyExchange.Text = "";

			List<CurrencyConversion> currencyConversion = fm.GetCurrencyConversionBy();
			foreach(CurrencyConversion c in currencyConversion)
			{
				stCurrencyExchange.Text += String.Format("{0}/{1} = {2:.####};  ", 
					c.SourceCurrency.Name, c.TargetCurrency.Name, c.ConversionRate);
			}
			
		}

		
		private void UpdateTimer_Tick(object sender, EventArgs e)
		{
			UpdateInfo();
		}

		private void PrintRAToolStripFileMenuItem_Click(object sender, EventArgs e)
		{
			if(RAGridView.SelectedCells.Count > 0)
			{
				new ExceptionCatcher().Execute(()=>
				                               {
												   RemittanceAdviceView ra = fm.GetRA(RAGridView.SelectedCells[0].RowIndex);
												   fm.PrintRemittanceAdvice(ra);
				                               });
				
			}
			else
			{
				MessageBox.Show("Пожалуйста, выберите платежное поручение", "Печать платежного поручения", MessageBoxButtons.OK,
				                MessageBoxIcon.Information);
			}
		}


		private void SendRAButton_Click(object sender, EventArgs e)
		{
			if(RAGridView.SelectedCells.Count > 0)
			{
				new ExceptionCatcher().Execute(() =>
				                               {
				                               	fm.SentRA(RAGridView.SelectedCells[0].RowIndex);
				                               	MessageBox.Show("Платежное поручение успешно отправлено", "Успешно",
				                               	                MessageBoxButtons.OK, MessageBoxIcon.Information);

				                               });
				RAGridView.Refresh(); 
			}
			if (RAGridView.SelectedCells.Count > 0)
			{
				RAGridView_CellEnter(sender, new DataGridViewCellEventArgs(0, RAGridView.SelectedCells[0].RowIndex));
			}
			else
			{
				RAGridView_CellEnter(sender, new DataGridViewCellEventArgs(0, -1));
			}
		}

		private void DeleteButton_Click(object sender, EventArgs e)
		{
			if (RAGridView.SelectedCells.Count > 0)
			{
				if (MessageBox.Show("Вы действительно хотите удалить платежное поручение?", "Удаление",
					MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
				{
					fm.RemoveRA(RAGridView.SelectedCells[0].RowIndex);
				}
			}
		}

		private void RAGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
		{
			RemittanceAdviceView ra = fm.GetRA(e.RowIndex);
			if (ra != null && !string.IsNullOrEmpty(ra.Status))
			{
				DeleteButton.Enabled = true;
				//btnPrintRA.Enabled = true;
				печатьToolStripMenuItem.Enabled = true;
				удToolStripMenuItem.Enabled = true;
				EditButton.Enabled = true;
				if ((RemittanceAdviceStatus)Enum.Parse(typeof(RemittanceAdviceStatus), ra.GetOriginalStatus()) == RemittanceAdviceStatus.ReadyToSign)
				{
					SendRAButton.Enabled = true;
					подписатьИОтправитьToolStripMenuItem.Enabled = true;
					btnPrintRA.Enabled = true;

				}else
				{
					SendRAButton.Enabled = false;
					подписатьИОтправитьToolStripMenuItem.Enabled = false;
					btnPrintRA.Enabled = false;
				}
			}
			else
			{
				SendRAButton.Enabled = false;
				DeleteButton.Enabled = false;
				btnPrintRA.Enabled = false;
				EditButton.Enabled = false;
				печатьToolStripMenuItem.Enabled = false;
				удToolStripMenuItem.Enabled = false;
				подписатьИОтправитьToolStripMenuItem.Enabled = false;
			}
		}

		private void контрагентыToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClientFormGridArea c = new ClientFormGridArea();

			c.StartPosition = FormStartPosition.CenterScreen;
			c.Show(fm);
		}

		private void счетаToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AccountFormGridArea b = new AccountFormGridArea();
			b.StartPosition = FormStartPosition.CenterScreen;
			b.Show(fm);
		}

		private void RAGridView_CellDoubleClick(object sender, EventArgs e)
		{
			if (RAGridView.SelectedCells.Count > 0)
			{
				fm.Param = RAGridView.SelectedCells[0].RowIndex;
				InvoiceForm f = new InvoiceForm();
				fm.Param = RAGridView.SelectedCells[0].RowIndex;
				if(f.Show(fm) != DialogResult.Yes)
				{
					RAGridView.DataSource = fm.GetAllRA();
				}
				RAGridView.Refresh();
				RAGridView_CellEnter(RAGridView, new DataGridViewCellEventArgs(0, RAGridView.SelectedCells[0].RowIndex));
				
				

				
			}

		}

		private void RAGridView_CellEnter(object sender, EventArgs e)
		{
			if (RAGridView.SelectedCells.Count > 0)
			{
				RAGridView_CellEnter(sender, new DataGridViewCellEventArgs(0, RAGridView.SelectedCells[0].RowIndex));
			}
			else
			{
				RAGridView_CellEnter(sender, new DataGridViewCellEventArgs(0, -1));
			}
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (MessageBox.Show(this, "Вы действительно хотите выйти?",
				"Выход", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
			{
				e.Cancel = true;
			}
		}

		private void UpdateRAButton_Click(object sender, EventArgs e)
		{
			UpdateInfo();
			SendedRaDataGridView.DataSource = fm.GetSendedRA();
			SendedRaDataGridView.Refresh();
			fm.SaveState();
		}

		private void EditButton_Click(object sender, EventArgs e)
		{
			if(RAGridView.SelectedCells.Count > 0)
			{
				fm.Param = RAGridView.SelectedCells[0].RowIndex;
				InvoiceForm f = new InvoiceForm();
				fm.Param = RAGridView.SelectedCells[0].RowIndex;
				if(f.Show(fm) != DialogResult.Yes)
				{
					RAGridView.DataSource = fm.GetAllRA();
				}
				RAGridView.Refresh();
				RAGridView_CellEnter(RAGridView, new DataGridViewCellEventArgs(0, RAGridView.SelectedCells[0].RowIndex));
			}
		}

		private void SendedRaDataGridView_DoubleClick(object sender, EventArgs e)
		{
			if (SendedRaDataGridView.SelectedCells.Count > 0)
			{
				fm.Param = new int[]{SendedRaDataGridView.CurrentRow.Index};
				InvoiceForm f = new InvoiceForm();
				f.Show(fm);
			}
		}

		private void DeleteSentRAButton_Click(object sender, EventArgs e)
		{
			if (SendedRaDataGridView.SelectedCells.Count > 0)
			{
				if (MessageBox.Show("Вы действительно хотите удалить платежное поручение?", "Удаление",
					MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
				{
					fm.GetSendedRA().RemoveAt(SendedRaDataGridView.CurrentRow.Index);
					SendedRaDataGridView.Refresh();
					fm.SaveState();
				}
			}
		}

		private void SendedRaDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			if(SendedRaDataGridView.SelectedCells.Count > 0)
			{
				DeleteSentRAButton.Enabled = true;
				EditSentRAButton.Enabled = true;
			}
			else
			{
				DeleteSentRAButton.Enabled = false;
				EditSentRAButton.Enabled = false;
			}
		}

		private void SendedRaDataGridView_SelectionChanged(object sender, EventArgs e)
		{
			SendedRaDataGridView_RowEnter(null, null);
		}

		private void EditSentRAButton_Click(object sender, EventArgs e)
		{
			if (SendedRaDataGridView.SelectedCells.Count > 0)
			{
				fm.Param = new int[] { SendedRaDataGridView.CurrentRow.Index };
				InvoiceForm f = new InvoiceForm();
				f.Show(fm);
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (SendedRaDataGridView.SelectedCells.Count > 0)
			{
				new ExceptionCatcher().Execute(() =>
				{
					RemittanceAdviceView ra = fm.GetSendedRAByInd(SendedRaDataGridView.SelectedCells[0].RowIndex);
					fm.PrintRemittanceAdvice(ra);
				});

			}
			else
			{
				MessageBox.Show("Пожалуйста, выберите платежное поручение", "Печать платежного поручения", MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void выпискаЗаПериодToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Statement st = new Statement();
			st.Show(fm);
		}

		private void настройкиToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SettingsForm f = new SettingsForm();
			f.Show(fm);
		}

		

		

	}
}
